package com.ip.user.service.impl;

import com.ip.user.mapper.SysUserMapper;
import com.ip.user.mapper.SysLoginLogMapper;
import com.ip.user.models.bo.UserBO;
import com.ip.user.models.dto.ChangePasswordDTO;
import com.ip.user.models.dto.UserLoginDTO;
import com.ip.user.models.dto.UserRegisterDTO;
import com.ip.user.models.service.SysUserService;
import com.ip.user.models.vo.SysLoginLogVO;
import com.ip.user.models.vo.UserVO;
import com.ip.user.util.PageUtil;
import com.ip.common.constant.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 系统用户服务实现类
 */
@DubboService
@Service
public class SysUserServiceImpl implements SysUserService {
    
    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private SysLoginLogMapper sysLoginLogMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    @Transactional
    public UserVO registerUser(UserRegisterDTO userRegisterDTO) {
        // 检查用户名是否已存在
        if (existsByUserName(userRegisterDTO.getUserName())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查身份证号是否已存在
        if (existsByIdCard(userRegisterDTO.getIdCard())) {
            throw new RuntimeException("身份证号已存在");
        }
        
        // 密码加密
        String encodedPassword = passwordEncoder.encode(userRegisterDTO.getPassword());
        userRegisterDTO.setPassword(encodedPassword);
        
        // 插入用户
        sysUserMapper.insertUser(userRegisterDTO);
        
        // 查询并返回注册的用户信息
        return sysUserMapper.selectUserByUserName(userRegisterDTO.getUserName());
    }
    
    @Override
    public UserVO login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUserName();
        String password = userLoginDTO.getPassword();
        
        // 根据用户名查询用户
        UserVO user = sysUserMapper.selectUserByUserName(username);
        
        // 记录登录日志
        if (user == null) {
            // 用户不存在也记录日志
            sysUserMapper.insertLoginLog(null, username, 0, "用户不存在");
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getUserStatus() != 1) {
            sysUserMapper.insertLoginLog(user.getUserId(), username, 0, "用户已被禁用");
            throw new RuntimeException("用户已被禁用");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            sysUserMapper.insertLoginLog(user.getUserId(), username, 0, "密码错误");
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 记录登录成功日志
        sysUserMapper.insertLoginLog(user.getUserId(), username, 1, null);
        
        return user;
    }
    
    @Override
    public UserVO getUserById(Integer userId) {
        return sysUserMapper.selectUserById(userId);
    }
    
    @Override
    public UserVO getUserByUserName(String userName) {
        return sysUserMapper.selectUserByUserName(userName);
    }
    
    @Override
    public UserVO getUserByIdCard(String idCard) {
        return sysUserMapper.selectUserByIdCard(idCard);
    }
    
    @Override
    public UserVO getUserByEmail(String email) {
        return sysUserMapper.selectUserByEmail(email);
    }
    
    @Override
    public List<UserVO> getAllUsers() {
        return sysUserMapper.selectAllUsers();
    }
    
    @Override
    public UserVO updateUser(UserBO userBO) {
        // 如果密码不为空，则对密码进行加密处理
        if (userBO.getPassword() != null && !userBO.getPassword().isEmpty()) {
            String encodedPassword = passwordEncoder.encode(userBO.getPassword());
            userBO.setPassword(encodedPassword);
        }
        
        sysUserMapper.updateUser(userBO);
        return sysUserMapper.selectUserById(userBO.getUserId());
    }
    
    @Override
    public void deleteUser(Integer userId) {
        sysUserMapper.deleteUser(userId);
    }
    
    @Override
    public boolean existsByUserName(String userName) {
        return sysUserMapper.selectUserByUserName(userName) != null;
    }
    
    @Override
    public boolean existsByIdCard(String idCard) {
        return sysUserMapper.selectUserByIdCard(idCard) != null;
    }
    
    @Override
    @Transactional
    public boolean changePassword(ChangePasswordDTO changePasswordDTO) {
        UserVO user = sysUserMapper.selectUserById(changePasswordDTO.getUserId());
        
        // 验证旧密码是否正确
        if (user == null || !passwordEncoder.matches(changePasswordDTO.getOldPassword(), user.getPassword())) {
            return false;
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(changePasswordDTO.getNewPassword());
        
        // 更新密码
        int result = sysUserMapper.updatePassword(changePasswordDTO.getUserId(), encodedPassword);
        
        return result > 0;
    }
    
    @Override
    @Transactional
    public boolean resetPasswordByEmail(String email) {
        logger.info("开始重置邮箱为 {} 的用户密码", email);
        
        // 根据邮箱查找用户
        UserVO user = sysUserMapper.selectUserByEmail(email);
        if (user == null) {
            logger.warn("未找到邮箱为 {} 的用户", email);
            return false;
        }
        
        logger.info("找到用户，用户ID: {}, 用户名: {}", user.getUserId(), user.getUserName());
        
        // 使用身份证号后6位作为默认密码
        if (user.getIdCard() != null && user.getIdCard().length() >= 6) {
            String defaultPassword = user.getIdCard().substring(user.getIdCard().length() - 6);
            logger.info("使用身份证号后六位作为默认密码: {}", defaultPassword);
            
            // 加密新密码
            String encodedPassword = passwordEncoder.encode(defaultPassword);
            logger.debug("密码加密完成");
            
            // 更新密码
            int result = sysUserMapper.updatePassword(user.getUserId(), encodedPassword);
            
            if (result > 0) {
                logger.info("用户 {} 的密码重置成功", user.getUserName());
            } else {
                logger.error("用户 {} 的密码更新失败，数据库更新返回结果: {}", user.getUserName(), result);
            }
            
            return result > 0;
        } else {
            logger.warn("用户 {} 的身份证号为空或长度不足6位，无法生成默认密码", user.getUserName());
            return false; // 身份证号为空或长度不足，无法生成默认密码
        }
    }
    
    @Override
    public PageResult<List<SysLoginLogVO>> getAllLoginLogs(int pageNo, int pageSize) {
        List<SysLoginLogVO> allLogs = sysLoginLogMapper.selectAllLogs();
        return PageUtil.paginate(allLogs, pageNo, pageSize);
    }
    
    @Override
    public PageResult<List<SysLoginLogVO>> getLoginLogsByConditions(LocalDateTime startTime, LocalDateTime endTime, Integer loginStatus, String userName, int pageNo, int pageSize) {
        List<SysLoginLogVO> logs = sysLoginLogMapper.selectLogsByConditions(startTime, endTime, loginStatus, userName);
        return PageUtil.paginate(logs, pageNo, pageSize);
    }
}